package com.liangtian.mdm.dm.common.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * Map对象与实体类的转换工具类
 *
 * @author zhangtao
 * @version 1.0
 * @since 2016-07-19
 */
public class BeanUtil {

    /**
     * 利用反射实现 将Map的值填充到Bean对应属性
     *
     * @param map 键值对集合map
     * @param obj 实体bean
     */
    public static void transMap2Bean(Map<String, Object> map, Object obj) {

        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();

                if (map.containsKey(key)) {
                    Object value = map.get(key);
                    // 得到property对应的setter方法
                    Method setter = property.getWriteMethod();
                    setter.invoke(obj, value);
                }
            }
        } catch (Exception e) {
            System.out.println("transMap2Bean Error " + e);
        }
        return;
    }

    /**
     * 利用反射将Bean属性值转化为Map键值对
     *
     * @param obj 实体对象
     * @return Map
     */
    public static Map<String, Object> transBean2Map(Map<String, Object> source, Object obj, boolean cover) {

        if (obj == null)
            return null;
        if (source == null)
            source = new HashMap<>();
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                // 不覆盖传入map的值
                if (!cover && source.containsKey(key)) continue;
                // 过滤class
                if (!key.equals("class")) {
                    // 得到property对应的getter方法
                    Method getter = property.getReadMethod();
                    Object value = getter.invoke(obj);

                    source.put(key, value);
                }
            }
        } catch (Exception e) {
            System.out.println("transBean2Map Error " + e);
        }
        return source;
    }


    /**
     * @param map<String, String> 键值对集合map
     * @param key         需要取值的key
     * @param defValue    返回的缺省值
     * @return String
     */
    public static String getValue(Map<String, String> map, String key, String defValue) {
        String value = map.get(key);
        if (value == null || "".equals(value))
            value = defValue;
        return value;
    }

}
